from django.shortcuts import render, redirect
from django.urls import reverse
from apps.book.models import Book, Author, Publisher
from apps.common.pagination import LxgPageNation


def book_list(request):
    """图书列表"""
    # books = Book.objects.all().order_by('-id')
    # 分页
    # page = LxgPageNation(request, books, 12)
    page = LxgPageNation(request, Book, 12)
    page_html = page.get_page_html()
    books = page.get_objects()
    return render(request, 'book/book/book_list.html', {
        'books': books,
        'page': page_html
    })


def book_add(request):
    """添加图书"""
    # POST
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        intro = request.POST.get('intro')
        pub_date = request.POST.get('pub_date')
        author_id = request.POST.get('author')
        author = Author.objects.get(id=author_id)
        publisher_id = request.POST.get('publisher')
        publisher = Publisher.objects.get(id=publisher_id)
        Book.objects.create(
            name=name,
            price=price,
            intro=intro,
            pub_date=pub_date,
            author=author,
            publisher=publisher
        )
        return redirect(reverse('book:book_list'))
    # GET
    authors = Author.objects.all().order_by('-id')
    publishers = Publisher.objects.all().order_by('-id')
    context = {
        'authors': authors,
        'publishers': publishers
    }
    return render(request, 'book/book/book_add.html', context)


def book_edit(request):
    """编辑图书"""
    # POST
    if request.method == 'POST':
        id = request.POST.get('id')
        name = request.POST.get('name')
        price = request.POST.get('price')
        intro = request.POST.get('intro')
        pub_date = request.POST.get('pub_date')
        author_id = request.POST.get('author')
        author = Author.objects.get(id=author_id)
        publisher_id = request.POST.get('publisher')
        publisher = Publisher.objects.get(id=publisher_id)
        book = Book.objects.get(id=id)
        book.name = name
        book.price = price
        book.intro = intro
        # 日期格式转换
        book.pub_date = pub_date
        book.author = author
        book.publisher = publisher
        book.save()
        return redirect(reverse('book:book_list'))

    # GET
    id = request.GET.get('id')
    book = Book.objects.get(id=id)
    book.pub_date = book.pub_date.strftime('%Y-%m-%d')
    context = {'book': book}
    authors = Author.objects.all().order_by('-id')
    context['authors'] = authors
    publishers = Publisher.objects.all().order_by('-id')
    context['publishers'] = publishers
    return render(request, 'book/book/book_edit.html', context)


def book_delete(request):
    """删除图书"""
    id = request.GET.get('id')
    Book.objects.get(id=id).delete()
    return redirect(reverse('book:book_list'))
